package crp.services.api.graphql.execution.error;

import com.qwlabs.lang.C2;
import com.qwlabs.exceptions.CodeException;
import com.qwlabs.exceptions.ConflictException;
import com.qwlabs.exceptions.ExternalException;
import com.qwlabs.exceptions.InternalServerException;
import com.qwlabs.exceptions.NotFoundException;
import com.qwlabs.exceptions.ServiceException;
import com.qwlabs.exceptions.ServiceValidationException;
import crp.services.api.shared.ErrorCodes;
import io.quarkus.runtime.StartupEvent;
import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.ForbiddenException;
import io.smallrye.graphql.execution.error.ErrorInfoMap;
import io.smallrye.graphql.schema.model.ErrorInfo;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import java.util.List;
import java.util.function.Function;

@ApplicationScoped
public class ErrorInfoMapRegister {
    private final List<ErrorInfo> errors = List.of(
            new ErrorInfo(CodeException.class.getName(), ErrorCodes.CODE_ERROR),
            new ErrorInfo(ConflictException.class.getName(), ErrorCodes.CONFLICT),
            new ErrorInfo(NotFoundException.class.getName(), ErrorCodes.NOT_FOUND),
            new ErrorInfo(AuthenticationFailedException.class.getName(), ErrorCodes.AUTHENTICATION_FAILED),
            new ErrorInfo(ServiceValidationException.class.getName(), ErrorCodes.SERVICE_VALIDATION),
            new ErrorInfo(ExternalException.class.getName(), ErrorCodes.INTERNAL_SERVER_ERROR),
            new ErrorInfo(InternalServerException.class.getName(), ErrorCodes.INTERNAL_SERVER_ERROR),
            new ErrorInfo(ServiceException.class.getName(), ErrorCodes.INTERNAL_SERVER_ERROR),
            new ErrorInfo(ForbiddenException.class.getName(), ErrorCodes.FORBIDDEN)
    );

    public void onStart(@Observes StartupEvent ev) {
        ErrorInfoMap.register(C2.map(errors, ErrorInfo::getClassName, Function.identity()));
    }
}
